package com.cubeofnine.sugar;

import java.util.List;
import java.util.Vector;

import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.View;
import android.view.animation.AnimationUtils;
import android.widget.EditText;
import android.widget.TextView;

import com.cubeofnine.sugar.business.AccountsBusiness;
import com.cubeofnine.sugar.inf.HomeInterface;
import com.cubeofnine.sugar.inf.OptionalInterface;
import com.cubeofnine.utils.ActivityParams;
import com.cubeofnine.utils.StringUtils;
import com.cubeofnine.utils.Validate;

public class FunctionAccountsAddActivity extends ActivityImpt implements
		HomeInterface, OptionalInterface {
	private static AccountsBusiness accountsBusiness = null;

	private static EditText accountName = null;
	private static EditText phoneNo = null;
	private static EditText website = null;

	// Thread and Handler Variables
	private static Handler handler;
	private Thread thread;

	private static Context context = null;
	private static String accountId = "";

	public String getClassName() {
		return FunctionAccountsAddActivity.class.getName();
	}

	@Override
	public void onCreate(Bundle savedInstanceState) {
		Log.i(getClassName(), "onCreate() : Start");

		super.onCreate(savedInstanceState);
		setContentView(R.layout.function_accounts_add);

		context = this;

		TextView headerTitle = (TextView) findViewById(R.id.header_title);
		headerTitle.setText(R.string.function_accounts);

		accountName = (EditText) findViewById(R.id.text_account_name);
		phoneNo = (EditText) findViewById(R.id.text_phone_no);
		website = (EditText) findViewById(R.id.text_website);

		try {
			boolean isOnline = isOnline();

			Log.d(getClassName(), "isOnline = " + isOnline);
			if (isOnline) {
				accountsBusiness = new AccountsBusiness(this);

				// Create a handler to update the UI
				handler = new Handler();

				// Check if the thread is already running
				thread = (Thread) getLastNonConfigurationInstance();
				if (thread != null && thread.isAlive()) {
					initProgressDialog(null);
				}
			} else {
				alertDialog(R.string.msg_no_connection);
			}

		} catch (Exception e) {
			Log.e(getClassName(), "onCreate()", e);
			alertDialog(R.string.msg_application_error);
		}

		Log.i(getClassName(), "onCreate() : End");
	}

	@Override
	public void onDestroy() {
		Log.i(getClassName(), "onDestroy() : Start");

		if (dialog != null && dialog.isShowing()) {
			dialog.dismiss();
			dialog = null;
		}

		Log.i(getClassName(), "onDestroy() : End");
		super.onDestroy();
	}

	@Override
	public void onRestart() {
		super.onRestart();
		Log.d(getClassName(), "onRestart()");
		finish();
	}

	// Save the thread
	@Override
	public Object onRetainNonConfigurationInstance() {
		Log.d(getClassName(), "onRetainNonConfigurationInstance()");
		return thread;
	}

	static public class SaveThread extends Thread {
		public static String getClassName() {
			return SaveThread.class.getName();
		}

		@Override
		public void run() {
			Log.i(getClassName(), "run() : Start");
			try {
				String accountNameValue = accountName.getText().toString()
						.trim();
				String phoneNoValue = phoneNo.getText().toString().trim();
				String websiteValue = website.getText().toString().trim();

				accountNameValue = StringUtils.encodeToken(accountNameValue);

				accountId = accountsBusiness.createAccount(accountNameValue,
						phoneNoValue, websiteValue);
			} catch (Exception e) {
				Log.e(getClassName(), "Connection Error", e);
				errorMessage = context.getString(R.string.msg_connection_error);
			} finally {
				Log.d(getClassName(), "Finally");
				handler.post(new SaveRunnable());
			}
			Log.i(getClassName(), "run() : End");
		}
	}

	static public class SaveRunnable implements Runnable {
		public static String getClassName() {
			return SaveRunnable.class.getName();
		}

		public void run() {
			Log.i(getClassName(), "run() : Start");
			Log.d(getClassName(), "errorMessage = " + errorMessage);

			if (errorMessage != null && !"".equals(errorMessage.trim())) {
				((ActivityImpt) context).alertDialog(errorMessage);
			} else {
				if (accountId != null && !accountId.isEmpty()) {
					((ActivityImpt) context).alertMessage(
							R.string.msg_successfully, true);

					AlertDialog.Builder adb = new AlertDialog.Builder(context);

					adb.setIcon(android.R.drawable.ic_dialog_alert);
					adb.setTitle(R.string.function_contacts);
					adb.setMessage(R.string.msg_new_contact);
					adb.setPositiveButton(R.string.button_yes,
							new DialogInterface.OnClickListener() {
								public void onClick(DialogInterface dialog,
										int which) {
									((FunctionAccountsAddActivity) context)
											.gotoCreateContact();
								}
							});
					adb.setNegativeButton(R.string.button_no,
							new DialogInterface.OnClickListener() {
								public void onClick(DialogInterface dialog,
										int which) {
									((FunctionAccountsAddActivity) context)
											.gotoViewAccount();
								}
							});
					adb.show();
				}
			}

			dialog.dismiss();

			Log.i(getClassName(), "run() : End");
		}
	}

	public void gotoCreateContact() {
		List<ActivityParams> params = new Vector<ActivityParams>();
		params.add(new ActivityParams(ContentDetailActivity.ACCOUNT_ID,
				accountId));
		gotoActivity(FunctionContactsAddActivity.class, params);
	}

	public void gotoViewAccount() {
		List<ActivityParams> params = new Vector<ActivityParams>();
		params.add(new ActivityParams(ContentDetailActivity.MODULE_NAME,
				AccountsBusiness.MODULE_ACCOUNTS));
		params.add(new ActivityParams(ContentDetailActivity.MODULE_ID,
				accountId));
		gotoActivity(ContentDetailActivity.class, params);
	}

	public void doSave() {
		String accountNameValue = accountName.getText().toString().trim();
		String phoneNoValue = phoneNo.getText().toString().trim();
		String websiteValue = website.getText().toString().trim();

		if (accountNameValue.isEmpty()) {
			alertDialog(R.string.msg_account_empty);
		} else if (phoneNoValue.isEmpty()) {
			alertDialog(R.string.msg_phone_no_empty);
		} else if (!Validate.isValidPhone(phoneNoValue)) {
			alertDialog(R.string.msg_phone_no_invalid);
		} else if (websiteValue.isEmpty()) {
			alertDialog(R.string.msg_website_empty);
		} else if (!Validate.isValidWebURL(websiteValue)) {
			alertDialog(R.string.msg_website_invalid);
		} else {
			initProgressDialog("Processing...");
			thread = new SaveThread();
			thread.start();
		}
	}

	public void onClickOptionalButton(View view) {
		view.startAnimation(AnimationUtils.loadAnimation(this,
				R.anim.image_click));
		// TODO Auto-generated method stub
		doSave();
	}

	public void onClickSearchButton(View view) {
		view.startAnimation(AnimationUtils.loadAnimation(this,
				R.anim.image_click));
		// TODO Auto-generated method stub

	}
}
